﻿namespace MultipleMonitorVideo.Models
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Runtime.Serialization.Json;

    public class BlueAllianceApi
    {
        private const string ApiUri = "http://www.thebluealliance.com/api";
        private const string TeamDetailsUri = ApiUri + "/v1/team/details";
        private const string MatchDetailsUri = ApiUri + "/v1/match/details";
        private const string EventsListUri = ApiUri + "/v1/events/list";
        
        public Team GetTeamDetails(int teamNumber)
        {
            string team = "frc" + teamNumber;
            string uri = TeamDetailsUri + "?team=" + team;

            Team teamDetails = BlueAllianceApi.GetJsonResponse(uri) as Team;

            return teamDetails;
        }

        public Match GetMatchDetails(IList<string> matches)
        {
            return this.GetMatchDetails(string.Join(",", matches));
        }

        public Match GetMatchDetails(string matches)
        {
            string uri = MatchDetailsUri + "?match=" + matches;

            Match match = BlueAllianceApi.GetJsonResponse(uri) as Match;

            return match;
        }

        public IList<Event> GetEventsList(int year)
        {
            string uri = EventsListUri + "?year=" + year;

            List<Event> events = BlueAllianceApi.GetJsonResponse(uri) as List<Event>;

            return events;
        }

        private static object GetJsonResponse(string uri)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.ContentType = "application/json";

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception(
                            string.Format(
                                "Server error (HTTP {0}: {1}).",
                                response.StatusCode,
                                response.StatusDescription));
                    }

                    Stream stream = response.GetResponseStream();

                    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Team));
                    object data = stream != null ? jsonSerializer.ReadObject(stream) : null;

                    return data;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                return null;
            }
        }
    }
}
